﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Volo.Abp.Caching;

namespace Abcd.DistributedCacheTest.ApiHost.Controllers
{
    [Route("api")]
    [ApiController]
    public class AbcdCacheTestController
    {
        #region DI
        private readonly IDistributedCache<DataCacheModel> _cache;

        public AbcdCacheTestController(IDistributedCache<DataCacheModel> cache)
        {
            _cache = cache;
        }
        #endregion


        [HttpGet]
        public async Task<DataCacheModel> GetDataAsync(Guid id)
        {
            var data = await _cache.GetOrAddAsync(
                id.ToString(),
                async ()=> await GetDataFromDatabaseAsync(id),
                () => new DistributedCacheEntryOptions()
                {
                    AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(5)
                });

            return data;
        }
         

        /// <summary>
        /// 假装从数据库拿数据
        /// </summary>
        private async Task<DataCacheModel> GetDataFromDatabaseAsync(Guid id)
        {
            await Task.CompletedTask; // 仅仅是为了不显示警告，工作中勿用

            Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss fff}  从数据库中拿到了数据。");

            // 假数据
            return new DataCacheModel
            {
                Id = id,
                Name = "Perry",
                Phone = "18012345677"
            };
        }
    }

    public class DataCacheModel
    {
        public Guid Id { get; set; }
        public string? Name { get; set; }
        public string? Phone { get; set; }
    }
}
